package com.bzb.secure.store.plugin

import android.content.Context
import android.os.Build
import android.util.Base64
import androidx.annotation.RequiresApi
import com.bzb.secure.store.plugin.KeyStoreManager.hexToByteArray
import com.bzb.secure.store.plugin.KeyStoreManager.toHexStr
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import java.security.interfaces.RSAPublicKey

/** SecureStorePlugin */
class SecureStorePlugin: FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel
  private lateinit var context : Context


  override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "plugin_secure_store")
    channel.setMethodCallHandler(this)
    context = flutterPluginBinding.applicationContext
  }

  override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
    when (call.method) {
      "generateRSA" -> {
        val alias = call.argument<String?>("alias")
        if (alias.isNullOrEmpty()) {
          result.error("1", "别名不能为空!", "")
          return
        }

        val keyPair = KeyStoreManager.generateKeyPair(alias, 1024)
        if (keyPair != null) {
//          if (keyPair is RSAPublicKey) {
//            println("modulus: ${KeyStoreManager.toHexString(keyPair.modulus.toByteArray())}")
//            println("publicExponent: ${KeyStoreManager.toHexString(keyPair.publicExponent.toByteArray())}")
//          }
          if (BuildConfig.DEBUG) {
            println("keyPub=${keyPair.encoded.size}")
            println("公钥: ${Base64.encodeToString(keyPair.encoded, Base64.NO_WRAP).trim()}")
          }

          // Android 端使用 Base64 编码的完整公钥,iOS 端使用 N 值, 使用 Base64.NO_WRAP 模式编码成整行
          result.success(Base64.encodeToString(keyPair.encoded, Base64.NO_WRAP).trim())
        } else {
          result.error("2", "密钥生成失败!", "")
        }
      }

      "encryptRSA" -> {
        val alias = call.argument<String?>("alias")
        val content = call.argument<String?>("content")

        if (alias.isNullOrEmpty()) {
          result.error("1", "别名不能为空!", "")
          return
        }
        if (content.isNullOrEmpty()) {
          result.error("1", "加密的数据不能为空!", "")
          return
        }

        val resultEncrypt = KeyStoreManager.encryptRSA(alias, content.toByteArray())
        if (resultEncrypt != null) {
          result.success(Base64.encodeToString(resultEncrypt, Base64.DEFAULT).trim())
        } else {
          result.error("2", "加密失败!", "")
        }
      }
      "decryptRSA" -> {
        val alias = call.argument<String?>("alias")
        val content = call.argument<String?>("content")

        if (alias.isNullOrEmpty()) {
          result.error("1", "别名不能为空!", "")
          return
        }
        if (content.isNullOrEmpty()) {
          result.error("1", "解密的数据不能为空!", "")
          return
        } else {
          val decode = Base64.decode(content, Base64.DEFAULT)
          if (decode == null) {
            result.error("1", "解密的数据是非法的!", "")
            return
          } else {
            println("解密: Base64 解码成功")
          }
          val resultDecrypt = KeyStoreManager.decryptRSA(alias, decode)
          if (resultDecrypt != null) {
            result.success(String(resultDecrypt).trim())
          } else {
            result.error("2", "解密失败!", "")
          }
        }
      }
      "decryptBigRSA" -> {
        val alias = call.argument<String?>("alias")
        val content = call.argument<String?>("content")

        if (alias.isNullOrEmpty()) {
          result.error("1", "别名不能为空!", "")
          return
        }
        if (content.isNullOrEmpty()) {
          result.error("1", "解密的数据不能为空!", "")
          return
        } else {
          val decode = Base64.decode(content, Base64.NO_WRAP)
          if (decode == null) {
            result.error("1", "解密的数据是非法的!", "")
            return
          } else {
            if (BuildConfig.DEBUG) {
              // decode.toHexStr 后是一段 1792 字符长度的 16进制 字符串
              println("解密: Base64 解码成功>>>${decode.toHexStr()}")
//              println("解密: Base64 解码成功, 第一段>>>${decode.toHexStr().substring(0, 500)}")
//              println("解密: Base64 解码成功, 第二段>>>${decode.toHexStr().substring(500, 1000)}")
//              println("解密: Base64 解码成功, 第三段>>>${decode.toHexStr().substring(1000, 1500)}")
//              println("解密: Base64 解码成功, 第四段>>>${decode.toHexStr().substring(1500)}")
            }
          }

          if (BuildConfig.DEBUG) {
            println("公钥: ${Base64.encodeToString(KeyStoreManager.generateKeyPair(alias, 1024)?.encoded ?: byteArrayOf(), Base64.NO_WRAP).trim()}")
          }

          // 测试分段加解密代码
//          val data = "3082015E041011223344556677881122334455667788041011223344556677881122334455667788043411223344551122334455112233445566778811223344556677881122334411223344556677881122334411223344556677881122048201008BE571B4F98FB2EE2A21A5420B7C4531AD3A0786027E394CEEED466EB047E0A3421879A03CD8282AE5DD4B38E3A9015B90A847420B0CADC74337B0197DEAD83667CF02569AB80F1058A06372BF6DCC584D21552855249980EE8071E571ECD8EEFF4EDC776A1C2691D53192FDB4EB8BBC263412E78DBF7E61178B9B346BB1A47336D487B59EF1D3A814D8857BD2C83ACFC1BF9093338789C8423D4D7723FE46BF1E32C829FB8A10718FAB5A0CD351F413A05F2571B12088554A9284D7BCDE415EE369C31D183D91901182415BA519D6C7DDE4E23262DC4C3D53325FB0C3AE3CD4D9A00CFC7DA72BAD4D46113087D0E505766A806C424D3B6E1A2ADA9888A83AD4"
//          val resultEncrypt = KeyStoreManager.encryptBigRSA(alias, data.toByteArray())
//          val base64 = Base64.encodeToString(resultEncrypt, Base64.DEFAULT)
//          println("加密结果: arrayLength=${resultEncrypt?.size}, toHexStr=${resultEncrypt?.toHexStr()}")
//          println("加密结果 Base64: strBase64Length=${base64.length}, resultEncryptBase64Str=${base64}")
//          val decode1 = Base64.decode(base64, Base64.DEFAULT)
//          println("解码 Base64: ${decode1.toHexStr()}")
//          val resultDecrypt = KeyStoreManager.decryptBigRSA(alias, decode1?: byteArrayOf())

          val resultDecrypt = KeyStoreManager.decryptBigRSA(alias, decode)
          if (resultDecrypt != null) {
            println("解密结果, 底层打印: ${String(resultDecrypt)}")
            result.success(String(resultDecrypt))
          } else {
            result.error("2", "解密失败!", "")
          }
        }
      }

      else -> {
        result.notImplemented()
      }
    }
  }

  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }
}
